import request from '@/common/request'
import dayjs from 'dayjs'
import { getTempId, createNewTask, nextRepeatDay } from '@/utils/taskList'

export default {
	namespaced: true,
	state: () => ({
		theme: "theme_2",
		userInfo: {},
		sortBy: "createTime",
		online: true, // 是否联网
		lastGeneralDate: null, // 每天首次打开时创建重复任务
		taskList: [],
		hasSyncIds: [], // 已经上传成功的临时id 下次拉取数据时删除临时数据 使用最新数据  
	}),
	mutations: {
		setState(state, payload) {
			const { key, value } = payload
			state[key] = value
		},
		setOnline(state, payload) {
			state.online = payload
		},
		setSortBy(state, payload) {
			state.sortBy = payload
		},
		setUserInfo(state, payload) {
			console.log('userInfo', payload)
			state.userInfo = payload
		},
		setTheme(state, payload) {
			state.theme = payload
		},
		setRepeat(state, papload) {
			const { repeatCircle, repeatUnit, repeatExtFields, repeatFlag, steps, taskContent, fileData, note, deadTime: deadTime$1 } = papload
			const deadTime = nextRepeatDay(papload, deadTime$1)
			this.commit('taskStore/addTaskItem', {
				props: {
					repeatCircle,
					repeatUnit,
					repeatExtFields,
					deadTime,
					steps: steps.map(item => ({ ...item, finishStatus: 0 })),
					taskContent,
					fileData,
					note
				},
				refresh: false
			})

		},
		addTaskItem(state, { props, refresh }) {
			state.taskList.push(createNewTask(props))

			refresh && this.dispatch('taskStore/updateTask')
		},
		updateTaskItem(state, { taskId, props }) {
			const target = state.taskList.find(item => item.taskId === taskId)
			const { repeatCircle, rpeatUnit, repeatUnit, repeatFlag, fromId } = target
			const restProps = { updated: 1 }
			if (props.finishStatus === 1 && repeatCircle && repeatUnit && !repeatFlag && !fromId) {
				this.commit('taskStore/setRepeat', target)
				restProps.repeatFlag = 1
			}
			Object.assign(target, props, restProps)
			console.log("正在更新的任务:", target)
			return this.dispatch('taskStore/updateTask')
		},

		deleteTaskItem(state, { taskId }) {
			if (typeof taskId === 'string') {
				const target = state.taskList.find(item => item.taskId === taskId)
				target.deleted = 1
			} else {
				state.taskList = state.taskList.filter(item => item.taskId !== taskId)
			}
			console.log(JSON.parse(JSON.stringify(state.taskList)), 'state.taskList')

			return this.dispatch('taskStore/updateTask')


		}
	},

	getter: {
		indexOfTask(state) {
			const idIndexMap = {}
			state.taskList.forEach((item, index) => {
				idIndexMap['taskId'] = item.taskId
			})
			return idIndexMap
		}
	},
	actions: {
		requestTasks({ state, getters, commit }, payload) {
			const { online, userInfo: { userId } } = state
			console.log("查询接口前置条件", online, userId)
			if (!online || !userId) return
			return request.postRequest("/api/task/gettask", { userId }).then(res => {
				const { data, code, msg } = res.data
				if (code === 200) {
					console.log("查询成功，返回内容为:", data)
					// 获取数据库任务列表  和本地对比
					// 返回数据id和index的映射
					const newTaskList = []
					const dataIdIndexMap = {}
					data.forEach((item, index) => {
						dataIdIndexMap[item.taskId] = index
					})

					state.taskList.forEach(task => {
						const { taskId, versionNum } = task
						if (typeof taskId === 'string') {
							const taskIndex = dataIdIndexMap[taskId]
							// 数据库的数据比较新
							if (taskIndex) {
								delete dataIdIndexMap[taskId] // 剩下的就是新增的了
								if (data[taskIndex].versionNum > versionNum) {
									newTaskList.push(data[taskIndex])
								} else {
									newTaskList.push(task)
								}
							} // taskId没找到 那就是被删除了
						} else if (typeof taskId === 'number') {
							if (!state.hasSyncIds.includes(taskId)) { // 如果没有进行提交 就还用本地的
								newTaskList.push(task)
							}
						}


					})

					state.hasSyncIds = [] // 清空已经上传还存在本地的临时id
					// 剩下的就是协同新增的了
					Object.values(dataIdIndexMap).forEach(index => {
						newTaskList.push(data[index])
					})
					commit("setState", { key: 'taskList', value: newTaskList })
					console.log("查询接口之后的任务列表", newTaskList, )
				} else {
					uni.showToast({
						title: msg,
						icon: "none",
						duration: 3000
					});
				}
			})
		},

		addTask({ state, dispatch }) {

			const addList = state.taskList.filter(item => typeof item.taskId === 'number')
			request.postRequest('/api/task/createtask', { list: addList.map((taskId, ...rest) => rest) }).then(res => {
				const { data, code, msg } = res.data
				if (code === 200) {
					state.hasSyncIds = addList.map(item => item.taskId)
				} else {
					uni.showToast({
						title: msg,
						icon: "none",
						duration: 3000
					});
				}

			})
		},
		updateTask({ state }) {
			const { online, userInfo: { userId } } = state
			console.log("上传接口前置条件", online, userId)
			if (!online || !userId) return
			const updateList = state.taskList.filter(task => {
				return typeof task.taskId === 'number' || task.updated || task.deleted
			})

			const formatList = updateList.map(task => {
				const { taskId, steps: steps$1, ...rest } = task
				const steps = steps$1.map(step => {
					const { stepId, ...rest } = step
					return typeof stepId === 'number' ? rest : step

				})
				return typeof taskId === 'number' ? { ...rest, steps } : { ...task, steps }
			})
			if(formatList.length===0){
				return
			}
			console.log('更新传给后端的数据', formatList)
			return request.postRequest('/api/task/updatetask', { list: formatList, userId }).then(res => {
				const { data, code, msg } = res.data
				if (code === 200) {

					state.hasSyncIds = updateList.filter(item => typeof item.taskId === 'number').map(item => item.taskId)
					console.log('即将删去的本地数据id', state.hasSyncIds)
				} else {
					uni.showToast({
						title: msg,
						icon: "none",
						duration: 3000
					});
				}
				this.dispatch('taskStore/requestTasks')
			})
		}
	}
}